<script lang="ts" setup>
import { QForm, type FormItemRows } from '@meetjs/element-plus-kit'
import { type FormRules, ElMessage } from 'element-plus'
import type { IGetDictsRes } from '@/api/system/dict/type'
import { addJob, updateJob, getJob } from '@/api/monitor/job'
import Crontab from './Crontab/index.vue'

const emits = defineEmits<{
	refresh: []
}>()

const props = defineProps<{
	jobGroupOptions: IGetDictsRes
}>()

const visible = ref(false)
const loading = ref(false)
const initLoading = ref(false)
const title = ref<'新增任务' | '编辑任务'>('新增任务')
const type = ref<'add' | 'edit'>('add')
const formRef = ref()
const baseFormData = {
	jobName: '',
	jobGroup: '',
	invokeTarget: '',
	cronExpression: '',
	misfirePolicy: '1',
	concurrent: '0'
}
const dialogFormValue = ref({ ...baseFormData })

const cronDialogVisible = ref(false)
const expression = ref('')

const dialogOptions = ref<FormItemRows[]>([
	{
		type: 'input',
		label: '任务名称',
		prop: 'jobName',
		attrs: {
			placeholder: '请输入任务名称',
			clearable: true
		}
	},
	{
		type: 'select',
		label: '任务分组',
		prop: 'jobGroup',
		options: [],
		attrs: {
			placeholder: '请选择任务分组',
			clearable: true
		}
	},
	{
		type: 'input',
		label: '调用方法',
		prop: 'invokeTarget',
		attrs: {
			placeholder: '请输入调用目标字符串',
			clearable: true
		}
	},
	{
		type: 'radio',
		label: '执行策略',
		prop: 'misfirePolicy',
		options: [
			{
				label: '立即执行',
				value: '1'
			},
			{
				label: '执行一次',
				value: '2'
			},
			{
				label: '放弃执行',
				value: '3'
			}
		]
	},
	{
		type: 'radio',
		label: '是否并发',
		prop: 'concurrent',
		options: [
			{
				label: '允许',
				value: '0'
			},
			{
				label: '禁止',
				value: '1'
			}
		]
	}
])

watch(
	() => props.jobGroupOptions,
	() => {
		dialogOptions.value[1].options = props.jobGroupOptions
	}
)
const rules = reactive<FormRules<{ [k: string]: any }>>({
	jobName: [
		{
			required: true,
			message: '请输入任务名称',
			trigger: 'blur'
		}
	],
	jobGroup: [
		{
			required: true,
			message: '请选择任务分组',
			trigger: 'change'
		}
	],
	invokeTarget: [
		{
			required: true,
			message: '请输入调用方法',
			trigger: 'blur'
		}
	],
	cronExpression: [
		{
			required: true,
			message: '请输入cron表达式',
			trigger: 'blur'
		}
	]
})

const init = async (operationType: 'add' | 'edit', jobId?: string) => {
	visible.value = true
	type.value = operationType
	title.value = operationType === 'add' ? '新增任务' : '编辑任务'

	// 根据操作类型初始化表单数据
	if (operationType === 'edit' && jobId) {
		initLoading.value = true
		try {
			// 编辑模式需要获取详细信息
			const { data } = await getJob(jobId)
			dialogFormValue.value = data
		} finally {
			initLoading.value = false
		}
	} else {
		// 新增模式：使用默认数据
		dialogFormValue.value = { ...baseFormData }
	}

	// 清理表单验证状态
	setTimeout(() => {
		formRef.value?.clearValidate()
	})
}

const handleShowCron = () => {
	expression.value = dialogFormValue.value.cronExpression
	cronDialogVisible.value = true
}

const crontabFill = (value: string) => {
	dialogFormValue.value.cronExpression = value
}

const submit = () => {
	formRef.value?.validate(async (valid: boolean) => {
		if (valid) {
			loading.value = true
			try {
				const apiFunc = type.value === 'add' ? addJob : updateJob
				await apiFunc({ ...dialogFormValue.value })
				const message = type.value === 'add' ? '新增成功' : '修改成功'
				ElMessage.success(message)
				visible.value = false
				emits('refresh')
			} finally {
				loading.value = false
			}
		}
	})
}

defineExpose({
	init
})
</script>

<template>
	<ElDialog
		v-model="visible"
		:title="title"
		:close-on-click-modal="false"
		:close-on-press-escape="false"
		width="800px"
	>
		<div
			v-loading="initLoading"
			element-loading-text="正在加载数据..."
			style="min-height: 400px"
		>
			<QForm
				v-if="!initLoading"
				ref="formRef"
				label-width="100px"
				:model="dialogFormValue"
				:form-options="dialogOptions"
				:rules="rules"
				:required="true"
				:gutter="20"
			/>
			<div
				v-if="!initLoading"
				class="mt-4"
			>
				<el-form-item
					label="cron表达式"
					label-width="100px"
					label-position="right"
					prop="cronExpression"
				>
					<el-input
						v-model="dialogFormValue.cronExpression"
						placeholder="请输入cron执行表达式"
						clearable
					>
						<template #append>
							<el-button
								type="primary"
								@click="handleShowCron"
							>
								生成表达式
								<i class="el-icon-time el-icon--right" />
							</el-button>
						</template>
					</el-input>
				</el-form-item>
			</div>
		</div>
		<template #footer>
			<el-button
				:disabled="loading"
				@click="visible = false"
			>
				取消
			</el-button>
			<el-button
				type="primary"
				:loading="loading"
				:disabled="initLoading"
				@click="submit"
			>
				确定
			</el-button>
		</template>
	</ElDialog>

	<ElDialog
		v-model="cronDialogVisible"
		title="生成cron表达式"
		width="700px"
	>
		<Crontab
			:expression="expression"
			@hide="cronDialogVisible = false"
			@fill="crontabFill"
		/>
	</ElDialog>
</template>

<style lang="scss" scoped></style>
